package com.wealth.system.web.controller;

import iaas.annotation.Log;
import iaas.enums.StatusEnum;
import iaas.utils.RedirectMessage;
import iaas.web.JqGridRequest;
import iaas.web.JqGridResponse;
import iaas.web.JqGridUtil;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.system.entity.Corporation;
import com.wealth.system.entity.Permission;
import com.wealth.system.entity.Role;
import com.wealth.system.entity.User;
import com.wealth.system.service.IPermissionService;
import com.wealth.system.service.IRoleService;
import com.wealth.system.service.IUserService;
import com.wealth.system.service.ShiroUser;

/**
 * 角色管理
 * @author chan
 *
 */
@Controller
@RequestMapping(value="/manage/system/role")
public class RoleController extends BaseController{

	Logger logger = Logger.getLogger(RoleController.class);
	
	@Autowired
	private IRoleService roleService;
	@Autowired
	private IPermissionService permissionService;
	@Autowired
	private IUserService userService;
	
	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Classify对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getrole(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
		try{
			if (id != -1) {
				Role role = roleService.get(id);
				model.addAttribute("role", role);
			}
		}catch(Exception e){
			logger.error("ModelAttribute方法出错！", e);
		}
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String toList(Model model){
		return "system/role/list";
	}
	
	
	/**
	 * 查询数据
	 */
	@RequestMapping(value="/list",method = RequestMethod.POST)
	@ResponseBody
	public JqGridResponse getJson(Model model,JqGridRequest request) {
		try{

			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			
			Page<Role> page = roleService.get(corpid, request,Role.class);
			
			return JqGridUtil.getJqGrirdResponse(page);
		}catch(Exception e){
			logger.error("列表出错！", e);
			return null;
		}
	}
	
	/**
	 * 创建角色页面
	 */
	@RequestMapping(value="/create",method = RequestMethod.GET)
	public String createForm(Model model){
		try{
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			List<Permission> permissionList = permissionService.getPermissionByCorpIdAndStatus(1L, StatusEnum.NORMAL.getValue());
			List<User> userList = userService.getUserByCorpIdAndStatus(corpid, StatusEnum.NORMAL.getValue());
			model.addAttribute("userList", userList);
			model.addAttribute("permissionList", permissionList);
			return "system/role/create";
		}catch(Exception e){
			logger.error("创建角色页面出错！", e);
			return null;
		}
	}
	
	/**
	 * 创建角色
	 */
	@Log(method="角色创建")
	@RequestMapping(value="/create",method = RequestMethod.POST)
	public String create(Model model,Role entity,RedirectAttributes redirectAttributes){
		try {
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			entity.setCreator(ShiroUser.getInstance().getUser().getUsername());
			entity.setCreatetime(new Date());
			entity.setStatus(StatusEnum.NORMAL.getValue());
			entity.setCorp(new Corporation(corpid));
			roleService.save(entity);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("创建角色成功"));
			return "redirect:/manage/system/role/list";
		} catch (Exception e) {
			logger.error("创建角色出错请联系工作人员解决！！", e);
			return "system/500";
		}
	}
	
	/**
	 * 编辑角色页面
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.GET)
	public String setUpdateForm(Model model,@PathVariable("id") Long id){
		try{
			Role role = roleService.get(id);
			model.addAttribute("role", role);
			
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			List<Permission> permissionList = permissionService.getPermissionByCorpIdAndStatus(1L, StatusEnum.NORMAL.getValue());
			List<User> userList = userService.getUserByCorpIdAndStatus(corpid, StatusEnum.NORMAL.getValue());
			model.addAttribute("userList", userList);
			model.addAttribute("permissionList", permissionList);
			
			return "system/role/update";
		}catch(Exception e){
			logger.error("编辑页面出错,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 修改角色信息
	 */
	@Log(method="角色修改")
	@RequestMapping(value="/update/{id}",method = RequestMethod.POST)
	public String update(@PathVariable("id") Long id,@ModelAttribute("role") Role role,RedirectAttributes redirectAttributes){
		try{
			roleService.save(role);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("编辑角色成功"));
			return "redirect:/manage/system/role/list";
		}catch(Exception e){
			logger.error("编辑角色出错,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 删除角色（逻辑删除）
	 */
	@RequestMapping(value="/delete/{id}",method = RequestMethod.GET)
	public String delete(Model model,@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			Role role = roleService.get(id);
			
			//删除用户对应的角色
			List<User>  userList = role.getUserList();
			for (User user : userList) {
				user.getRoleList().remove(role);
				userService.save(user);
			}
			roleService.deleteLogical(id);
			
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("删除角色成功"));
			return "redirect:/manage/system/role/list";
		}catch(Exception e){
			logger.error("删除角色出错,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 停用
	 */
	@RequestMapping(value="/disable/{id}",method = RequestMethod.GET)
	public String disable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			roleService.updateStatus(id, StatusEnum.STOP.getValue());
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("停用成功"));
			return "redirect:/manage/system/role/list";
		}catch(Exception e){
			logger.error("停用错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 启用
	 */
	@RequestMapping(value="/enable/{id}",method = RequestMethod.GET)
	public String enable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			roleService.updateStatus(id, StatusEnum.NORMAL.getValue());
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("启用成功"));
			return "redirect:/manage/system/role/list";
		}catch(Exception e){
			logger.error("启用错误,id="+id,e);
			return "system/500";
		}
	}
	
}
